from flask import Blueprint, render_template, request, jsonify

from applications.common.curd import model_to_dicts
from applications.common.utils.http import table_api
from applications.models import Lesson , Emotion
from applications.schemas import LessonOutSchema,EmotionOutSchema
from applications.extensions import db
import os
import face_recognition
import numpy as np
import cv2
from keras.models import load_model

admin_lesson = Blueprint('adminLesson', __name__, url_prefix='/admin/lesson')


@admin_lesson.get('/')
def main():
    return render_template('admin/lesson/main.html')



@admin_lesson.get('/data')
def data():
    lessons = Lesson.query.layui_paginate()
    return table_api(data=model_to_dicts(schema=LessonOutSchema, data=lessons.items), count=lessons.total)



@admin_lesson.get('/emotion/<int:_id>')
def emotion(_id):
    file = r'D:\学生情绪'
    result = []
    for root, dirs, files in os.walk(file):
        for file in files:
            path = os.path.join(root,file)
            stuName = file.split('.')[0]
            lesson = Lesson.query.filter_by(id=_id).first()
            emotion_dict= {'生气': 0, '悲伤': 5, '中性': 4, '厌恶': 1, '惊讶': 6, '恐惧': 2, '高兴': 3}

            image = face_recognition.load_image_file(path)
            # 载入图像
            face_locations = face_recognition.face_locations(image)
            # 寻找脸部
            top, right, bottom, left = face_locations[0]
            # 将脸部框起来

            face_image = image[top:bottom, left:right]
            face_image = cv2.resize(face_image, (48,48))
            face_image = cv2.cvtColor(face_image, cv2.COLOR_BGR2GRAY)
            face_image = np.reshape(face_image, [1, face_image.shape[0], face_image.shape[1], 1])
            # 调整到可以进入该模型输入的大小

            model = load_model("D:\\model_v6_23.hdf5")
            # 载入模型

            predicted_class = np.argmax(model.predict(face_image))
            # 分类情绪
            label_map = dict((v,k) for k,v in emotion_dict.items())
            predicted_label = label_map[predicted_class]
            # 根据情绪映射表输出情绪
            print(predicted_label)


            role = Emotion(
                student_name=stuName,
                emotion=predicted_label,
                lesson_name=lesson.name
            )
            db.session.add(role)
            db.session.commit()

            result.append("学生：【"+stuName+"】,该课程情绪为：【"+predicted_label+"】")

    return jsonify(result)



@admin_lesson.get('/stuEmo')
def stuEmo():
    return render_template('admin/lesson/emotion.html')




@admin_lesson.get('/stuEmoData')
def stuEmoData():
    emotions = Emotion.query.layui_paginate()
    return table_api(data=model_to_dicts(schema=EmotionOutSchema, data=emotions.items), count=emotions.total)
